package com.scheduling.user.service;

import com.scheduling.common.result.Result;
import com.scheduling.common.result.ResultCode;
import com.scheduling.common.security.jwt.JwtService;
import com.scheduling.user.dto.UserLoginRequest;
import com.scheduling.user.dto.UserLoginResponse;
import com.scheduling.user.dto.UserRegisterRequest;
import com.scheduling.user.entity.User;
import com.scheduling.user.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtService jwtService;

    @Override
    public Result<Void> register(UserRegisterRequest request) {
        try {
            // 检查用户名是否已存在
            if (userMapper.countByUsername(request.getUsername()) > 0) {
                return Result.error(ResultCode.DATA_ALREADY_EXISTS.getCode(), "用户名已存在");
            }

            // 创建新用户
            User user = new User();
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setUsername(request.getUsername());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setCreateTime(LocalDateTime.now());

            // 保存用户
            int result = userMapper.insertUser(user);
            if (result > 0) {
                log.info("用户注册成功: {}", request.getUsername());
                return Result.success();
            } else {
                log.warn("用户注册失败: {}", request.getUsername());
                return Result.error(ResultCode.BUSINESS_ERROR.getCode(), "注册失败");
            }

        } catch (Exception e) {
            log.error("用户注册异常: {}", request.getUsername(), e);
            return Result.error(ResultCode.ERROR.getCode(), "系统错误");
        }
    }

    @Override
    public Result<UserLoginResponse> login(UserLoginRequest request) {
        try {
            // 查找用户
            User user = userMapper.findByUsername(request.getUsername());
            if (user == null) {
                log.warn("登录失败，用户不存在: {}", request.getUsername());
                return Result.error(ResultCode.USER_NOT_FOUND.getCode(), "用户不存在");
            }

            // 验证密码
            if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
                log.warn("登录失败，密码错误: {}", request.getUsername());
                return Result.error(ResultCode.PASSWORD_ERROR.getCode(), "密码错误");
            }

            // 生成JWT Token
            String token = jwtService.generateToken(user.getUserId());
            Long tokenExpire = System.currentTimeMillis() + 7200000; // 2小时后过期

            UserLoginResponse response = new UserLoginResponse(
                    user.getUserId(),
                    user.getUsername(),
                    token,
                    tokenExpire
            );

            log.info("用户登录成功: {}", request.getUsername());
            return Result.success(response);

        } catch (Exception e) {
            log.error("用户登录异常: {}", request.getUsername(), e);
            return Result.error(ResultCode.ERROR.getCode(), "系统错误");
        }
    }

    @Override
    public Result<Void> logout(HttpServletRequest request) {
        try {
            // 从请求头获取token
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "未找到有效token");
            }

            // 从token中提取用户ID
            String userId = jwtService.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "无效token");
            }

            // 将用户的所有token失效
            jwtService.invalidateUserTokens(userId);
            log.info("用户退出登录成功: {}", userId);
            return Result.success();
        } catch (Exception e) {
            log.error("用户退出登录失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "退出登录失败");
        }
    }

    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    @Override
    public Result<Void> deleteAccount(String userId) {
        try {
            User user = userMapper.findByUserId(userId);
            if (user == null) {
                return Result.error(ResultCode.USER_NOT_FOUND.getCode(), "用户不存在");
            }

            // 使该用户的所有token失效
            jwtService.invalidateUserTokens(userId);

            // 删除用户数据
            int deletedRows = userMapper.deleteByUserId(userId);
            if (deletedRows > 0) {
                log.info("用户账户注销成功: {}", userId);
                return Result.success();
            } else {
                log.warn("用户账户注销失败，未删除任何记录: {}", userId);
                return Result.error(ResultCode.ERROR.getCode(), "账户注销失败");
            }

        } catch (Exception e) {
            log.error("用户账户注销异常: {}", userId, e);
            return Result.error(ResultCode.ERROR.getCode(), "系统错误");
        }
    }
}

